package com.example.testcamara;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 通用工具类，只做功能实现，不和业务交互
 */
public class GeneralUtils {
    private static Camera camera;
    private static boolean openFlashLight = false;

    private GeneralUtils() {}

    /**
     * 打开/关闭手电筒
     */
    public static void flashlightEvent(Context context, int type) {
        boolean openLight = type == 1;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            setTorchMode(context, openLight);
        } else {
            try {
                Camera.Parameters parameters;
                if (openLight && !openFlashLight) {
                    camera = Camera.open();
                    camera.startPreview();
                    parameters = camera.getParameters();
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);// 开启
                    camera.setParameters(parameters);
                    openFlashLight = true;
                } else if (!openLight && openFlashLight) {
                    if (camera == null) {
                        return;
                    }
                    parameters = camera.getParameters();
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);// 关闭
                    camera.setParameters(parameters);
                    camera.release();
                    camera = null;
                    openFlashLight = false;
                }
            } catch (Exception e) {
            }

        }
    }

    /**
     * 开启/关闭闪光灯
     *
     * @param enabled
     * @return 是否成功开启闪关灯
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static boolean setTorchMode(Context context, boolean enabled) {
        CameraManager mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        if (mCameraManager == null) {
            return false;
        }
        boolean openSuccess = true;
        String cameraId = getCameraId(mCameraManager);
        if (cameraId == null) {
            return false;
        }
        try {
            mCameraManager.setTorchMode(cameraId, enabled);
        } catch (Exception exception) {
            openSuccess = false;
        }
        return openSuccess;
    }

    /**
     * 获取闪关灯有效的 cameraId
     *
     * @return
     */
    public static String getCameraId(CameraManager mCameraManager) {
        try {
            if (mCameraManager != null) {
                String[] ids = mCameraManager.getCameraIdList();
                for (String id : ids) {
                    CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
                    Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                    Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
                    if (flashAvailable != null && flashAvailable
                            && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
                        return id;
                    }
                }
            }
        } catch (CameraAccessException e) {
        }
        return null;
    }

    private static final String PREFIX_FILE = "file://";

    /**
     * 获取视频第一帧缩略图
     *
     * @return bitmap
     */
    public static Bitmap getVideoThumbBmp(String videoPath) {
        if (TextUtils.isEmpty(videoPath)) {
            return null;
        }
        if (videoPath.startsWith(PREFIX_FILE)) {
            videoPath = videoPath.substring(PREFIX_FILE.length());
        }
        if (!new File(videoPath).exists()) {
            return null;
        }

        MediaMetadataRetriever media = new MediaMetadataRetriever();
        // videoPath 本地视频的路径
        media.setDataSource(videoPath);
        return media.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
    }


    public static String getFileMD5(Context context, String filepath) {
        File file = new File(progressPath(context, filepath));
        if(!file.exists()){
            return "";
        }
        return getLocalFileMD5(file);
    }

    /**
     * 获取指定文件的md5
     * @param file
     * @return
     */
    private static String getLocalFileMD5(File file) {
        try {
            FileInputStream fileStream = new FileInputStream(file);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];

            int length;
            while((length = fileStream.read(buffer)) != -1) {
                md5.update(buffer, 0, length);
            }

            fileStream.close();
            byte[] md5Bytes = md5.digest();
            StringBuilder hexValue = new StringBuilder();

            for(int i = 0; i < md5Bytes.length; ++i) {
                int val = md5Bytes[i] & 255;
                if(val < 16) {
                    hexValue.append("0");
                }

                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (Throwable var9) {
            var9.printStackTrace();
            return null;
        }
    }

    private static final String DOMAIN_FILE = "file://";
    public static String progressPath(Context context, final String path) {
        if(TextUtils.isEmpty(path)) {
            return "";
        }
        final String uri = PathUtil.processPath(context, path);
        if(TextUtils.isEmpty(uri)) {
            return path;
        }
        if (uri.startsWith(DOMAIN_FILE)) {
            String noSchemeUrl = getNoSchemeUrl(uri);
//            String uriPath = PathUtils.processUriPath(context, noSchemeUrl);
//            if (uriPath != null) {
//                return uriPath;
//            } else {
                return uri.substring(DOMAIN_FILE.length());
//            }
        }
        // 如果不是file协议，直接返回输入参数；
        return path;
    }

    private static final int LEN_SCHEMA_SPLIT = "://".length();

    /**
     * 获取.ajx定义的文件索引
     */
    public static String getNoSchemeUrl(final String url){
        if(TextUtils.isEmpty(url)){
            return url;
        }
        final Uri uri = Uri.parse(url);
        final String schema = uri.getScheme();
        if(!TextUtils.isEmpty(schema)){
            return url.substring(schema.length() + LEN_SCHEMA_SPLIT);
        }
        return url;
    }

    public static long getFileLength(Context context, String filepath){
        File file = new File(progressPath(context, filepath));
        if(!file.exists()){
            return 0;
        }
        return getLocalFileSize(file);
    }

    private static long getLocalFileSize(File file)  {
        long size = 0;
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                size = fis.available();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return size;
    }
}

